package communicationsPORTS;
import java.io.*;
import java.util.*;

import GUI.MessWindow;

import gnu.io.*;

public class Communication {
	
	   //static CommPortIdentifier portIdIN;
	   InputStream          inputStream;
	   OutputStream         outputStream;
	   SerialPort           serialPortIN;
	   SerialPort           serialPortOUT;
	  // Thread           	readThread;
	   MessWindow mWindowTemp;
	   
	   Stack<MessageGPS> stack = new Stack<MessageGPS>();
	   
	   //messageGPS 			wiadomosc;
	   //static String        messageString = "Hello, world!";
	   //static OutputStream  outputStream;
	   static boolean       outputBufferEmptyFlag = false;
	  // MessWindow mWindow = new MessWindow("GPS input");
//	   Listner list;
	
	public Communication( MessWindow mWindow) throws Exception
	{
		//reader = new sluchacz();
		mWindowTemp = mWindow;
		mWindow.show();
	}
	
	public Communication(CommPortIdentifier PortIN, MessWindow mWindow) throws Exception
	{
		//System.out.println("Przed sluchacz");
		mWindowTemp = mWindow;
		new Listner(PortIN, mWindow);
		mWindow.show();
	}
	
	public Communication(String PortNameIN, MessWindow mWindow) throws Exception
	{
		new Listner(new Ports().getPortId(PortNameIN),  mWindow);
		mWindowTemp = mWindow;
		mWindow.show();
	}
	
	public Communication(String portNameIN, String portNameOUT, MessWindow mWindow)throws Exception {
		// TODO Auto-generated constructor stub
		new Listner(new Ports().getPortId(portNameIN), mWindow);
		mWindowTemp = mWindow;
		CommPortIdentifier PortOUT = new Ports().getPortId(portNameOUT);
		serialPortOUT = (SerialPort) PortOUT.open("SimpleReadApp", 2000);
		outputStream = serialPortOUT.getOutputStream();
		mWindow.show();
	}

	public Stack<MessageGPS> getStackMessageGPS(){
		return stack;
	}
	
	public void removeFirstStackMessageGPS(){
		stack.remove(0);
	}
	
	public void writeOutCOM(String output){
		try {
			outputStream.write(output.getBytes());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			mWindowTemp.addText(new Date().toString() + " " + e.toString() + "\n","ERROR" );
		}
	}
	
//@SuppressWarnings("restriction")
//public class sluchacz implements Runnable, SerialPortEventListener{

public class Listner implements SerialPortEventListener{ 	
	   
	public Listner(CommPortIdentifier PortIN, MessWindow mWindow) {
		      // initalize serial port
		      try {
		         serialPortIN = (SerialPort) PortIN.open("SimpleReadApp", 2000);
		      } catch (PortInUseException e) {
		    	 		    	  
		      }
		   
		      try {
		    	  
		         inputStream = serialPortIN.getInputStream();
		      } catch (IOException e) {}
		   
		      try {
		         serialPortIN.addEventListener(this);
		      } catch (TooManyListenersException e) {}
		      
		      // activate the DATA_AVAILABLE notifier
		      serialPortIN.notifyOnDataAvailable(true);
		   
		      try {
		         // set port parameters
		         serialPortIN.setSerialPortParams(9600, SerialPort.DATABITS_8, 
		                     SerialPort.STOPBITS_1, 
		                     SerialPort.PARITY_NONE);
		      } catch (UnsupportedCommOperationException e) {}
		      
		      // start the read thread
		    //  readThread = new Thread();
		     // readThread.start();
		      
		   }
	
	   public void serialEvent(SerialPortEvent event) {
		      switch (event.getEventType()) {
		      case SerialPortEvent.BI:
		      case SerialPortEvent.OE:
		      case SerialPortEvent.FE:
		      case SerialPortEvent.PE:
		      case SerialPortEvent.CD:
		      case SerialPortEvent.CTS:
		      case SerialPortEvent.DSR:
		      case SerialPortEvent.RI:
		      case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
		         break;
		      case SerialPortEvent.DATA_AVAILABLE:
		        		    	
		        byte[] readBuffer = new byte[20000];
		         
		        try {
		            while (inputStream.available() > 0) {
		            	inputStream.read(readBuffer);
		            } 
		            
		            String result = new String(readBuffer);
		           // mWindowTemp.addText(result.trim(), "GPSOUT");
		            stack.add( new MessageGPS(result.trim(),mWindowTemp));
		            //wiadomosc = new messageGPS(result.trim());
		            //System.out.println("Stack size: " + stack.size());
		         } catch (IOException e) {}
		         break;
		      }
		   }
	
	
	/*   public void initwritetoport() {
		      // initwritetoport() assumes that the port has already been opened and
		      //    initialized by "public nulltest()"

		      try {
		         // get the outputstream
		         outputStream = serialPort.getOutputStream();
		      } catch (IOException e) {}

		      try {
		         // activate the OUTPUT_BUFFER_EMPTY notifier
		         serialPort.notifyOnOutputEmpty(true);
		      } catch (Exception e) {
		         System.out.println("Error setting event notification");
		         System.out.println(e.toString());
		         System.exit(-1);
		      }
		      
		   }

		   public void writetoport() {
		      System.out.println("Writing \""+messageString+"\" to "+serialPort.getName());
		      try {
		         // write string to serial port
		         outputStream.write(messageString.getBytes());
		      } catch (IOException e) {}
		   }*/


	
	   /*public void run() {
		      // first thing in the thread, we initialize the write operation
		     initwritetoport();
		      try {
		         while (true) {
		            // write string to port, the serialEvent will read it
		            writetoport();
		            Thread.sleep(10);
		         }
		      } catch (InterruptedException e) {}
		   } */

   
	 }

//public class 

}



